<template>
  <div class="contact-container">
    <!-- 顶部添加好友区域 -->
    <div class="contact-header">
      <div style="display: flex; align-items: center; gap: 16px">
        <button @click="goBack" class="back-btn"><BackwardOutlined /> 返回</button>
        <h2>联系人</h2>
      </div>
      <button @click="showAddFriendModal = true" class="add-friend-btn">
        <PlusOutlined /> 添加好友
      </button>
    </div>

    <!-- 好友申请提示区域 -->
    <div class="request-notification" v-if="hasFriendRequests">
      <div class="notification-content">
        <span>您有 {{ friendRequestCount }} 条好友申请</span>
        <button @click="handleFriendRequests" class="handle-btn">处理</button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <Input
        placeholder="搜索好友"
        v-model:value="searchKeyword"
        :prefix="searchIcon"
        @pressEnter="searchFriends"
      />
    </div>

    <!-- 联系人标签页 -->
    <Tabs v-model:activeKey="activeTab" class="contact-tabs">
      <TabPane key="friends" tab="好友" />
      <TabPane key="groups" tab="群聊" />
    </Tabs>

    <!-- 联系人列表 -->
    <div class="contact-list">
      <template v-if="activeTab === 'friends'">
        <div v-if="friends.length === 0" class="empty-state">
          <UserOutlined class="empty-icon" />
          <p>暂无好友</p>
          <button @click="showAddFriendModal = true" class="add-btn">添加好友</button>
        </div>
        <div v-else>
          <div v-for="friend in friends" :key="friend.id" class="contact-item">
            <div class="avatar" :style="{ background: getAvatarColor(friend.name) }">
              <img
                v-if="friend.avatar && friend.avatar.startsWith('http')"
                :src="friend.avatar"
                :alt="friend.name"
                class="avatar-image"
              />
              <span v-else>{{ friend.name.charAt(0) }}</span>
            </div>
            <div class="contact-info">
              <h3>{{ friend.name }}</h3>
              <p class="contact-desc">{{ friend.desc || '暂无个性签名' }}</p>
            </div>
          </div>
        </div>
      </template>

      <template v-else-if="activeTab === 'groups'">
        <div v-if="groups.length === 0" class="empty-state">
          <TeamOutlined class="empty-icon" />
          <p>暂无群聊</p>
          <button @click="showCreateGroupModal = true" class="add-btn">创建群聊</button>
        </div>
        <div v-else>
          <div v-for="group in groups" :key="group.id" class="contact-item">
            <div class="avatar" :style="{ background: getAvatarColor(group.name) }">
              <img
                v-if="group.avatar && group.avatar.startsWith('http')"
                :src="group.avatar"
                :alt="group.name"
                class="avatar-image"
              />
              <span v-else>{{ group.name.charAt(0) }}</span>
            </div>
            <div class="contact-info">
              <h3>{{ group.name }}</h3>
              <p class="contact-desc">{{ group.descrption || group.memberCount + ' 名成员' }}</p>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 添加好友弹窗 -->
    <Modal
      v-model:visible="showAddFriendModal"
      title="添加好友"
      @ok="sendFriendRequest"
      @cancel="showAddFriendModal = false"
    >
      <div class="modal-content">
        <p>搜索用户:</p>
        <Input
          placeholder="输入用户名或邮箱"
          v-model:value="friendSearchKeyword"
          :prefix="searchIcon"
          @pressEnter="searchFriendsQuanju"
          @blur="searchFriendsQuanju"
          class="search-input"
        />
        <div v-if="searchResults.length > 0" class="search-results">
          <div v-for="user in searchResults" :key="user.id" class="search-result-item">
            <div class="avatar" :style="{ background: getAvatarColor(user.name) }">
              {{ user.name.charAt(0) }}
            </div>
            <div class="user-info">
              <h4>{{ user.name }}</h4>
              <p class="email">{{ user.email }}</p>
            </div>
            <button @click="selectUser(user)" class="select-btn">选择</button>
          </div>
        </div>
        <div v-else-if="friendSearchKeyword" class="no-results">未找到用户</div>

        <div v-if="selectedUser" class="selected-user">
          <p>已选择:</p>
          <div class="user-info">
            <div class="avatar" :style="{ background: getAvatarColor(selectedUser.name) }">
              {{ selectedUser.name.charAt(0) }}
            </div>
            <div>
              <h4>{{ selectedUser.name }}</h4>
              <p class="email">{{ selectedUser.email }}</p>
            </div>
          </div>
          <Input.TextArea
            placeholder="添加验证信息..."
            v-model:value="friendRequestMessage"
            class="message-input"
          />
        </div>
      </div>
    </Modal>

    <!-- 好友申请处理弹窗 -->
    <Modal
      v-model:visible="showFriendRequestModal"
      title="好友申请"
      @cancel="showFriendRequestModal = false"
      @ok="showFriendRequestModal = false"
    >
      <div class="request-list">
        <div v-for="request in friendRequests" :key="request.id" class="request-item">
          <div class="avatar" :style="{ background: getAvatarColor(request.fromName) }">
            {{ request.fromName.charAt(0) }}
          </div>
          <div class="request-info">
            <h4>{{ request.fromName }}</h4>
            <p class="request-message">{{ request.message }}</p>
          </div>
          <div class="action-buttons">
            <button @click="acceptRequest(request.id)" class="accept-btn">接受</button>
            <button @click="rejectRequest(request.id)" class="reject-btn">拒绝</button>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, h, onUnmounted } from 'vue'
import {
  PlusOutlined,
  SearchOutlined,
  UserOutlined,
  TeamOutlined,
  BackwardOutlined
} from '@ant-design/icons-vue'
import { Input, Tabs, TabPane, Modal, message, Menu } from 'ant-design-vue'
import {
  loadContactUsersUsingPost,
  searchFriendsUsingPost,
  sendAddFriendUsingPost,
  getApplyFriendUsingPost
} from '@/api/contactController'
import { useUserStore } from '@/stores/user'

// 图标定义
const searchIcon = h(SearchOutlined)
const backIcon = h(BackwardOutlined)

// 返回上一页
const goBack = () => {
  window.history.back()
}

// 状态管理
const showAddFriendModal = ref(false)
const showFriendRequestModal = ref(false)
const showCreateGroupModal = ref(false)
const searchKeyword = ref('')
const friendSearchKeyword = ref('')
const friendRequestMessage = ref('')
const selectedUser = ref<any>(null)
const searchResults = ref<any[]>([])
const activeTab = ref('friends')
const friends = ref<any[]>([])
const groups = ref<any[]>([])
const friendRequests = ref<any[]>([])
const hasFriendRequests = computed(() => friendRequests.value.length > 0)
const friendRequestCount = computed(() => friendRequests.value.length)
const userStore = useUserStore()

// 模拟数据 - 实际项目中应通过API获取
const mockFriends = [
  { id: 1, name: '张三', desc: '喜欢编程和音乐' },
  { id: 2, name: '李四', desc: '热爱运动和旅行' },
  { id: 3, name: '王五', desc: '美食爱好者' }
]

const mockGroups = [
  { id: 1, name: '开发团队', memberCount: 10 },
  { id: 2, name: '技术交流', memberCount: 50 },
  { id: 3, name: '兴趣小组', memberCount: 15 }
]

const mockFriendRequests = [
  { id: 1, fromName: '赵六', message: '你好，我是赵六，很高兴认识你！' },
  { id: 2, fromName: '钱七', message: '我们在GitHub上有过互动，希望能成为好友' }
]

// 加载联系人数据
onMounted(async () => {
  // 检查ipcRenderer是否存在
  listening()

  try {
    // 实际项目中应调用API加载数据
    const response = await loadContactUsersUsingPost()
    console.log('response', response)

    // 处理API返回的数据
    if (response && response.data.status === 'success' && response.data) {
      // 处理联系人数据
      if (response.data.data?.contactUsers && Array.isArray(response.data.data.contactUsers)) {
        friends.value = response.data.data.contactUsers.map((user: any) => ({
          id: user.userId,
          name: user.nickName,
          desc: user.sex === 1 ? '男' : user.sex === 0 ? '女' : '未知',
          avatar: user.avator ? user.avator.trim() : ''
        }))
      }

      // 处理群组数据
      if (response.data.data?.contactQunVOS && Array.isArray(response.data.data?.contactQunVOS)) {
        groups.value = response.data.data?.contactQunVOS.map((group: any) => ({
          id: group.qunId,
          name: group.qunName,
          descrption: group.descrption,
          avatar: group.avator ? group.avator.trim() : '',
          memberCount: 0 // API中没有提供成员数量，默认为0
        }))
      }
    } else {
      // 如果API返回数据不符合预期，使用模拟数据
      friends.value = mockFriends
      groups.value = mockGroups
    }

    getApplyFriend()
  } catch (error) {
    message.error('加载联系人失败')
    console.error('Failed to load contacts:', error)
    // 发生错误时使用模拟数据
    friends.value = mockFriends
    groups.value = mockGroups
    friendRequests.value = mockFriendRequests
  }
})
const getApplyFriend = async () => {
  const response = await getApplyFriendUsingPost()
  if (response.data.status === 'success') {
    friendRequests.value = response.data.data
  } else {
    message.error(response.data.info)
  }
}

const listening = () => {
  window.electron.ipcRenderer.on('friendRequest', (event, request) => {
    console.log('收到好友申请:', request.messageContent)
    console.log('好友申请详情:', JSON.stringify(request))
    // 将新的好友申请添加到数组开头
    friendRequests.value.unshift(request.messageContent)
    // 显示通知或提示
    message.info(`收到好友申请`)
  })
}
// 组件卸载时移除监听
onUnmounted(() => {
  window.electron.ipcRenderer.removeAllListeners('friendRequest')
})

// 搜索好友
const searchFriends = async () => {
  console.log('----------------------------')

  if (!friendSearchKeyword.value.trim()) {
    searchResults.value = []
    return
  }

  // 模拟搜索结果 - 实际项目中应调用API
  searchResults.value = [
    { id: 4, name: '孙八', email: 'sunba@example.com' },
    { id: 5, name: '周九', email: 'zhoujiu@example.com' }
  ].filter(
    (user) =>
      user.name.includes(friendSearchKeyword.value) ||
      user.email.includes(friendSearchKeyword.value)
  )
}
const searchFriendsQuanju = async () => {
  searchResults.value = []
  const response = await searchFriendsUsingPost({
    searchKeyWord: friendSearchKeyword.value
  })
  searchResults.value = Array.isArray(response.data.data) ? response.data.data : []
}
// 选择用户
const selectUser = (user: any) => {
  selectedUser.value = user
  searchResults.value = []
}

// 发送好友申请
const sendFriendRequest = async () => {
  if (!selectedUser.value) {
    message.warning('请先选择好友')
    return
  }
  console.log(selectedUser.value)
  const response = await sendAddFriendUsingPost({
    receiverId: selectedUser.value.id,
    content: friendRequestMessage.value
  })
  if (response.data.status === 'success') {
    message.success(`好友申请已发送给 ${selectedUser.value.name}`)
  } else {
    message.error(response.data.info)
  }
  // 模拟发送请求 - 实际项目中应调用API

  showAddFriendModal.value = false
  selectedUser.value = null
  friendSearchKeyword.value = ''
  friendRequestMessage.value = ''
}

// 处理好友申请
const handleFriendRequests = () => {
  showFriendRequestModal.value = true
}

// 接受好友申请
const acceptRequest = async (requestId: number) => {
  // 模拟接受请求 - 实际项目中应调用API
  friendRequests.value = friendRequests.value.filter((req) => req.id !== requestId)
  friends.value.push({
    id: requestId + 100,
    name: mockFriendRequests.find((req) => req.id === requestId)?.fromName || '',
    desc: '新好友'
  })
  message.success('已接受好友申请')
}

// 拒绝好友申请
const rejectRequest = async (requestId: number) => {
  // 模拟拒绝请求 - 实际项目中应调用API
  friendRequests.value = friendRequests.value.filter((req) => req.id !== requestId)
  message.success('已拒绝好友申请')
}

// 生成头像颜色
const getAvatarColor = (name: string) => {
  const colors = [
    '#667eea',
    '#8b5cf6',
    '#ec4899',
    '#06b6d4',
    '#10b981',
    '#f59e0b',
    '#ef4444',
    '#6366f1',
    '#d946ef',
    '#0ea5e9'
  ]
  let hash = 0
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash)
  }
  const index = Math.abs(hash % colors.length)
  return colors[index]
}
</script>

<style scoped>
.contact-container {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.contact-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.contact-header h2 {
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
}

.add-friend-btn {
  display: flex;
  align-items: center;
  padding: 6px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.add-friend-btn:hover {
  background: #556cd6;
}

.add-friend-btn svg {
  margin-right: 6px;
}

.back-btn {
  display: flex;
  align-items: center;
  padding: 6px 16px;
  background: #f1f5f9;
  color: #64748b;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #e2e8f0;
  color: #475569;
}

.request-notification {
  background: #fef3c7;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 24px;
}

.notification-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-content span {
  color: #92400e;
}

.handle-btn {
  padding: 4px 12px;
  background: #f59e0b;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.handle-btn:hover {
  background: #d97706;
}

.search-container {
  margin-bottom: 24px;
}

.contact-tabs {
  margin-bottom: 24px;
  border-bottom: 1px solid #e2e8f0;
}

.contact-list {
  flex: 1;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.contact-item:hover {
  background-color: #f1f5f9;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  margin-right: 16px;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.contact-info {
  flex: 1;
}

.contact-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 4px 0;
}

.contact-desc {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #64748b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #cbd5e1;
}

.add-btn {
  margin-top: 16px;
  padding: 6px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.add-btn:hover {
  background: #556cd6;
}

.modal-content {
  padding: 16px 0;
}

.search-input {
  margin-bottom: 16px;
}

.search-results {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  margin-bottom: 16px;
}

.search-result-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-result-item:hover {
  background-color: #f1f5f9;
}

.user-info {
  flex: 1;
}

.user-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 4px 0;
}

.email {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.select-btn {
  padding: 4px 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.select-btn:hover {
  background: #556cd6;
}

.no-results {
  color: #64748b;
  padding: 16px;
  text-align: center;
}

.selected-user {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.message-input {
  margin-top: 16px;
  width: 100%;
}

.request-list {
  max-height: 300px;
  overflow-y: auto;
}

.request-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.request-item:last-child {
  border-bottom: none;
}

.request-info {
  flex: 1;
  margin-left: 16px;
}

.request-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 4px 0;
}

.request-message {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.accept-btn {
  padding: 4px 12px;
  background: #10b981;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.accept-btn:hover {
  background: #059669;
}

.reject-btn {
  padding: 4px 12px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.reject-btn:hover {
  background: #dc2626;
}
</style>
